package com.example.rabbitmq.controller;

import com.example.rabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Author: 以默
 * @Date: 2024/7/19 10:53
 *  发送延迟消息
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable("message") String message) {
        log.info("当前时间：{}，发送一条信息给TTL队列：{}", new Date().toString(),message);
        rabbitTemplate.convertAndSend("X", "XA","消息来自ttl为10s的队列："+message);
        rabbitTemplate.convertAndSend("X", "XB","消息来自ttl为40s的队列："+message);
    }


    // 开始发消息 消息TTL
    @GetMapping("sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message") String message,@PathVariable("ttlTime") String ttlTime) {
        log.info("当前时间：{}，发送一条市场{}毫秒TTL信息给TTL队列：{}", new Date().toString(),ttlTime,message);
        rabbitTemplate.convertAndSend("X", "XC",message,(msg ->{
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        }));
    }

    // 开始发消息 基于插件的消息及延迟时间
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable String message,@PathVariable Integer delayTime){
        log.info("当前时间：{}，发送一条延迟{}毫秒的信息给延迟队列delayed.queue：{}", new Date().toString(),delayTime,message);
        // 发送消息
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_QUEUE_NAME,DelayedQueueConfig.DELAYED_ROUTING_KEY,message,(msg ->{
            msg.getMessageProperties().setDelay(delayTime);
            return msg;
        }));
    }

}
